import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  ElementRef,
  ViewChildren,
  QueryList,
  SimpleChanges
} from '@angular/core';
import { List } from 'linqts';
// 报警级别、类别数据模型
import { FaultLevel } from '../../../../entity/fault-level.model';
import { TurbComponent } from '../../../../entity/turbcomponent.model';
import { FaultData } from '../../../../entity/fault-data';
import { AlarmCategory } from '../../../../entity/alarm-category.model';
import {
  ITdDataTableColumn,
  TdDataTableComponent,
  IPageChangeEvent,
  TdDataTableService,
  TdDialogService,
  ITdDataTableSortChangeEvent,
  TdDataTableSortingOrder
} from '@covalent/core';

import { FaultLevelService } from '../../../../service/fault_level.service';
import { AlarmCategoryService } from '../../../../service/alarm-category.service';
import { TurbcomponentService } from '../../../../service/turbcomponent.service';

// 列表数据模型
import {
  AlarmSearchData,
  FaultCount,
  FaultTableData
} from '../alarm-search.data';
import { DataSourceService } from '../../../../service/data-source/data-source.service';
import { ApplicationService } from '../../../../service/application.service';
import { DatePipe } from '@angular/common';
import { InterceptorService } from '../../../../service/interceptor/interceptor-service';
import { LazyLoadEvent } from 'primeng/primeng';

@Component({
  selector: 'app-alarm-list',
  templateUrl: './alarm-list.component.html',
  styleUrls: ['./alarm-list.component.css'],
  providers: [DataSourceService]
})
export class AlarmListComponent implements OnInit {
  /**
   * 报警类别数据集合
   * @type @memberof AlarmListComponent
   */
  public alarmCategoryDatas: AlarmSearchData[] = [];
  public active: number = 0;
  private h = 1000 * 3600;
  /**
   * 故障等级数据集合
   * @type @memberof AlarmListComponent
   */
  public faultLevels: FaultLevel[] = [];

  /**
   * 故障统计数据集合
   * @type @memberof AlarmListComponent
   */
  public faultCountData: FaultCount[] = [];
  public faultCountList: FaultCount[] = [];
  public pages: number;

  // 故障类别数据集合
  public turbComponents: TurbComponent[] = [];

  // 列表数据集合
  private faultDatas: FaultData[] = [];
  @ViewChild('alarmTable')
  alarmTable: ElementRef;
  row: number;

  @ViewChild('countTable')
  countTable: ElementRef;
  rowC: number;
  /**
   * 风机id集合
   *
   * @type @memberof AlarmListComponent
   */
  @Input() turbineIds: number[] = [];
  @Input() startTime: Date;
  @Input() endTime: Date;
  /**
   * 故障描述模糊查询
   *
   * @memberof AlarmListComponent
   */
  @Input() divFaultDesc: string;
  @Output() createData = new EventEmitter<boolean>();

  /* faultData1: FaultTableData[] = [];
  faultData2: FaultTableData[] = [];

  // 统计数据
  faultData3: FaultCount[] = [];
  faultData4: FaultCount[] = []; */

  datasource: AlarmSearchData[];
  totalRecords: number;

  sortO: number = -1;
  sortF = 'faultCount';
  sortFO: number = -1;
  sortFault = 'faultCode';
  /**
   * 报警描述变化定时器
   *
   * @type {*}
   * @memberof AlarmListComponent
   */
  timer: any;

  /**
   *是否显示加载进度条
   *
   * @type {*}
   * @memberof AlarmListComponent
   */
  timerIsShow: any;
  /**
   * 是否显示进度条
   */
  isShowBar: boolean = true;
  /**
   * 分页中，每页显示的条数
   */
  public pageSize: number;

  public codes: string[] = ['01'];
  private count = 0;
  constructor(
    private _dialogService: TdDialogService,
    private dataSource: DataSourceService,
    private alarmCategoryService: AlarmCategoryService,
    private faultLevelService: FaultLevelService,
    private turbcomponentService: TurbcomponentService,
    private application: ApplicationService,
    private http: InterceptorService,
    private datePipe: DatePipe
  ) {}

  ngOnInit() {
    if (
      this.application.currentMenuParams &&
      this.application.currentMenuParams['pageSize']
    ) {
      this.pageSize = Number(
        this.application.currentMenuParams['pageSize'].paramValue
      );
    } else {
      this.pageSize = 15;
    }
    Promise.all([
      this.alarmCategoryService.getAlarmCategorys(),
      this.faultLevelService.getBasicFaultLevelListByDeviceCategoryCodes(
        this.codes
      ),
      this.turbcomponentService.getTurbComponents()
    ])
      .then(res => {
        let turbFilter: TurbComponent[] = [];
        if (res[2]) {
          turbFilter = res[2].filter(
            o => o.parentId === 0 || o.parentId == null
          );
        }
        this.initData(res[0], res[1], turbFilter);
      })
      .catch(error => {
        console.log('app-alarm-list has error', error);
      });
  }
  ngOnDestroy(): void {
    if (this.dataSource != null) this.dataSource.dispose();
  }
  ngOnChanges(changes: SimpleChanges) {
    if (changes['divFaultDesc']) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        if (this.alarmCategoryDatas) {
          this.faultCountDataFilter();
        }
      }, 1000);
    }
  }
  initData(
    categorys: AlarmCategory[],
    faultLevels: FaultLevel[],
    turbComponents: TurbComponent[]
  ) {
    if (!categorys || !faultLevels) {
      return false;
    }
    categorys.forEach((category, index) => {
      let faultLevelsArr: FaultLevel[] = [];
      let turbComponentsArr: TurbComponent[] = [];

      if (category.alarmCategoryId === 1) {
        category.alarmCategoryName = '故障';
      }

      // 通过遍历，给对象重新赋值，改变地址指向
      faultLevels.forEach(o => {
        let faultLevel = {
          faultLevelId: o.faultLevelId,
          faultLevelName: o.faultLevelName,
          soundId: o.soundId,
          unAlarm: o.unAlarm,
          faultLevelColor: o.faultLevelColor,
          faultLevelDesc: o.faultLevelDesc,
          faultLevelWeight: o.faultLevelWeight,
          content: o.content,
          soundContent: o.soundContent,
          faultLevelCount: o.faultLevelCount,
          isChecked: o.isChecked
        };

        faultLevelsArr.push(faultLevel);
      });

      turbComponents.forEach(k => {
        const turbComp = {
          turbComponentId: k.turbComponentId,
          turbComponentName: k.turbComponentName,
          turbComponentSeq: k.turbComponentSeq,
          turbComponentIcon: k.turbComponentIcon,
          turbComponentDesc: k.turbComponentDesc,
          turbComponentCount: k.turbComponentCount,
          isChecked: k.isChecked
        };
        turbComponentsArr.push(turbComp);
      });

      const alarmCategoryData: AlarmSearchData = {
        alarmCategoryId: category.alarmCategoryId,
        alarmCategoryName: category.alarmCategoryName,
        faultDatas: [],
        faultTableData: [],
        faultCounts: [],
        faultCountsData: [],
        faultTable: [],
        isChecked: index === 0 ? true : false,
        faultLevelTotals: faultLevelsArr,
        turbComponentTotals: turbComponentsArr
      };

      this.alarmCategoryDatas.push(alarmCategoryData);
    });
    this.createData.emit(true);
    this.isShowBar = false;
    // this.upData() //初始化获取数据
  }
  public onAlarmCategoryClick(alarmCategpry: AlarmSearchData) {
    alarmCategpry.isChecked = true;
    const alarmCategprys = this.alarmCategoryDatas.filter(
      o => o.alarmCategoryId !== alarmCategpry.alarmCategoryId
    );
    if (alarmCategprys && alarmCategprys.length > 0) {
      alarmCategprys.map(o => (o.isChecked = false));
    }
  }
  loadData(next: FaultData[]): any {
    // this.faultDatas=[...next];
    this.faultDatas.push(...next);
    this.faultDatas.sort((a, b) => {
          return Number(b.faultCode) - Number(a.faultCode);
    });
    // this.faultDatas = [...next];
    this.alarmCategoryDatas.forEach((category, i) => {
      // 表格统计数据集合
      const faultsList: FaultTableData[] = [];
      category.faultDatas = [];
      category.faultCounts = [];
      category.faultTableData = [];
      const faultData = this.faultDatas.filter(
        o => o.alarmCategoryId === category.alarmCategoryId
      );

      const faultsAllCount = [...faultData];
      faultData.forEach(fault => {
        const faultList: FaultTableData = {
          modelName: fault.modelName,
          factoryName: fault.factoryName,
          farmName: fault.farmName,
          deviceName: fault.deviceName,
          faultCode: fault.faultCode,
          desc: fault.farmName + fault.deviceName + fault.faultDesc,
          faultLevelName: fault.faultLevelName,
          components:
            fault.turbComponentName +
            '-' +
            fault.subcomponentName +
            '-' +
            fault.partsName,
          faultLevelColor: fault.faultLevelColor,
          faultTime: fault.faultTime,
          faultEndTime: fault.faultEndTime,
          faultLevelId: fault.faultLevelId,
          turbComponentId: fault.turbComponentId,
          turbComponent: fault.turbComponentName,
          subcomponentName: fault.subcomponentName,
          partsName: fault.partsName,
          faultDesc: fault.faultDesc
        };
        if (fault.faultEndTime) {
          faultList.faultContinueTime = Number(
            (
              (new Date(fault.faultEndTime).getTime() -
                new Date(fault.faultTime).getTime()) /
              1000 /
              60 /
              60
            ).toFixed(2)
          );
        } else {
          faultList.faultContinueTime = null;
        }
        faultsList.push(faultList);
      });
      category.faultLength = faultData.length;

      const faults: FaultTableData[] = faultsList; // .slice(0, 15);
      /* faults.sort((a, b) => {
            return new Date(b.faultTime).getTime() - new Date(a.faultTime).getTime();
          }); */
      category.faultTableData = [...faults];
      category.faultTable = [...faults];
      if (category.faultDatas) {
        const list = new List(faultData);
        // 计算报警等级数量
        category.faultLevelTotals.forEach(level => {
          level.faultLevelCount = list.Count(
            o => o.faultLevelId === level.faultLevelId
          );
        });

        // 计算报警类别数量
        category.turbComponentTotals.forEach(turbComponent => {
          turbComponent.turbComponentCount = list.Count(
            o => o.turbComponentId === turbComponent.turbComponentId
          );
        });
      }

      // 按code和风机统计报警数量
      const counts: FaultCount[] = [];
      let faultCountsData: FaultCount[] = [];
      // 按code分组
      const listCode = new List(faultsAllCount);
      const groupsCode = listCode.GroupBy(
        grouper => grouper.faultCode,
        mapper => mapper
      );
      const codes = Object.getOwnPropertyNames(groupsCode);
      codes.forEach(code => {
        const codeList = new List<FaultData>(
          Object.getOwnPropertyDescriptor(groupsCode, code).value
        );
        const codeListArray = new List<FaultData>(
          Object.getOwnPropertyDescriptor(groupsCode, code).value
        ).ToArray();

        // code分组后，按风机名称分组
        const listTurb = new List(codeListArray);
        const groupsTurb = listTurb.GroupBy(
          grouper => grouper.deviceName,
          mapper => mapper
        );
        const Turbs = Object.getOwnPropertyNames(groupsTurb);
        Turbs.forEach(turb => {
          const turbList = new List<FaultData>(
            Object.getOwnPropertyDescriptor(groupsTurb, turb).value
          );
          const turbListArray = new List<FaultData>(
            Object.getOwnPropertyDescriptor(groupsTurb, turb).value
          ).ToArray();

          const timeWork = turbList.Sum(
            o =>
              new Date(o.faultEndTime).getTime() -
              new Date(o.faultTime).getTime()
          );
          const faultCountData: FaultCount = {
            faultCode: code,
            faultDesc: turbListArray[0].faultDesc,
            faultLevelColor: turbListArray[0].faultLevelColor,
            farmName: turbListArray[0].farmName,
            deviceName: turbListArray[0].deviceName,
            faultCount: turbList.Count(),
            faultWorkTime: Number((timeWork / this.h).toFixed(2))
          };
          counts.push(faultCountData);
        });
      });
      faultCountsData = [...counts];
      category.faultCountLength = faultCountsData.length;

      const faultsC: FaultCount[] = faultCountsData; // .slice(0, 17);
      category.faultCounts = [...faultsC];
      category.faultCountsData = [...faultsC];
    });
    if (this.active === 0) {
      this.row = Math.floor(
        (this.alarmTable.nativeElement.clientHeight - 100) / 40
      );
      this.rowC = Math.floor(
        (this.alarmTable.nativeElement.clientHeight + 50) / 40
      );
    } else {
      this.row = Math.floor(
        (this.countTable.nativeElement.clientHeight - 150) / 40
      );
      this.rowC = Math.floor(
        (this.countTable.nativeElement.clientHeight - 50) / 40
      );
    }
    this.isShowBar = false;
    this.faultCountDataFilter();

  }

  upData() {
    this.isShowBar = true;
    if (this.dataSource != null) {
      this.dataSource.dispose();
    }
    this.dataSource = new DataSourceService(this.http, this.datePipe);
    this.faultDatas = [];
    this.count = 0;
    this.alarmCategoryDatas.forEach(o => (o.faultDatas = []));
    this.alarmCategoryDatas.forEach(o => (o.faultCounts = []));
    this.alarmCategoryDatas.forEach(o => (o.faultTableData = []));
    let segment = 0;
    this.dataSource.alarmHistory(this.startTime, this.endTime, this.turbineIds).subscribe(next => {
        if (next.hasOwnProperty('segment')) {
          segment = Number(next['segment']);
        }else {
          ++this.count;
        if (this.count === segment) {
          this.isShowBar = false;
        }
        if (!next || !next.length) {
          return false;
        }
        setTimeout(this.loadData(next), 1000);
        }
        // this.alarmCategoryDatas = [];
        // console.log(this.alarmCategoryDatas)
      });
    /* this.dataSource.history.getTurbineFaults(this.turbineIds, this.startTime, this.endTime)
      .then(res => {
        // console.log(res)

        if (!res) { return false; };
        // this.faultDatas.push(...res);
        this.faultDatas = [...res];
        this.alarmCategoryDatas.forEach((category, i) => {
          // 表格统计数据集合
          const faultsList: FaultTableData[] = [];
          category.faultDatas = [];
          category.faultCounts = [];
          category.faultTableData = [];
          const faultData = this.faultDatas.filter(o => o.alarmCategoryId === category.alarmCategoryId);

          const faultsAllCount = [...faultData];
          faultData.forEach(fault => {
            const faultList = {
              modelName: fault.modelName,
              factoryName: fault.factoryName,
              farmName: fault.farmName,
              deviceName: fault.deviceName,
              faultCode: fault.faultCode,
              desc: fault.farmName + fault.deviceName + fault.faultDesc,
              faultLevelName: fault.faultLevelName,
              components: fault.turbComponentName + '-' + fault.subcomponentName + '-' + fault.partsName,
              faultLevelColor: fault.faultLevelColor,
              faultTime: fault.faultTime,
              faultEndTime: fault.faultEndTime,
              faultContinueTime: Number(((new Date(fault.faultEndTime).getTime() - new Date(fault.faultTime).getTime()) / 1000 / 60 / 60).toFixed(2)),
              faultLevelId: fault.faultLevelId,
              turbComponentId: fault.turbComponentId,
              turbComponent: fault.turbComponentName,
              subcomponentName: fault.subcomponentName,
              partsName: fault.partsName,
              faultDesc: fault.faultDesc,
            };
            faultsList.push(faultList);
          });
          category.faultLength = faultData.length;

          const faults: FaultTableData[] = faultsList; // .slice(0, 15);
          category.faultTableData = [...faults];
          category.faultTable = [...faults];
          if (category.faultDatas) {
            const list = new List(faultData);
            // 计算报警等级数量
            category.faultLevelTotals.forEach(level => {
              level.faultLevelCount = list.Count(o => o.faultLevelId === level.faultLevelId);
            });

            // 计算报警类别数量
            category.turbComponentTotals.forEach(turbComponent => {
              turbComponent.turbComponentCount = list.Count(o => o.turbComponentId === turbComponent.turbComponentId);
            });
          }

          // 按code和风机统计报警数量
          const counts: FaultCount[] = [];
          let faultCountsData: FaultCount[] = [];
          // 按code分组
          const listCode = new List(faultsAllCount);
          const groupsCode = listCode.GroupBy(grouper => grouper.faultCode, mapper => mapper);
          const codes = Object.getOwnPropertyNames(groupsCode);
          codes.forEach(code => {
            const codeList = new List<FaultData>(Object.getOwnPropertyDescriptor(groupsCode, code).value);
            const codeListArray = new List<FaultData>(Object.getOwnPropertyDescriptor(groupsCode, code).value).ToArray();

            // code分组后，按风机名称分组
            const listTurb = new List(codeListArray);
            const groupsTurb = listTurb.GroupBy(grouper => grouper.deviceName, mapper => mapper);
            const Turbs = Object.getOwnPropertyNames(groupsTurb);
            Turbs.forEach(turb => {
              const turbList = new List<FaultData>(Object.getOwnPropertyDescriptor(groupsTurb, turb).value);
              const turbListArray = new List<FaultData>(Object.getOwnPropertyDescriptor(groupsTurb, turb).value).ToArray();

              const timeWork = turbList.Sum(o => new Date(o.faultEndTime).getTime() - new Date(o.faultTime).getTime());
              const faultCountData: FaultCount = {
                faultCode: code,
                faultDesc: turbListArray[0].faultDesc,
                faultLevelColor: turbListArray[0].faultLevelColor,
                farmName: turbListArray[0].farmName,
                deviceName: turbListArray[0].deviceName,
                faultCount: turbList.Count(),
                faultWorkTime: Number((timeWork / this.h).toFixed(2))
              };
              counts.push(faultCountData);
            });
          });
          faultCountsData = [...counts];
          category.faultCountLength = faultCountsData.length;

          const faultsC: FaultCount[] = faultCountsData; // .slice(0, 17);
          category.faultCounts = [...faultsC];
          category.faultCountsData = [...faultsC];
        });
        if (this.active === 0) {
          this.row = Math.floor((this.alarmTable.nativeElement.clientHeight - 100) / 40);
          this.rowC = Math.floor((this.alarmTable.nativeElement.clientHeight + 50) / 40);
        } else {
          this.row = Math.floor((this.countTable.nativeElement.clientHeight - 150) / 40);
          this.rowC = Math.floor((this.countTable.nativeElement.clientHeight - 50) / 40);
        };
        this.faultCountDataFilter();
        this.isShowBar = false;

        // this.alarmCategoryDatas = [];
        // console.log(this.alarmCategoryDatas)

      })
      .catch(error => {
        //this._message.info('获得时间段内的报警信息' + error, { nzDuration: 3000 });
      }); */
  }
  faultCountDataFilter() {
    this.alarmCategoryDatas.forEach((alarmCategoryData, i) => {
      if (this.divFaultDesc != '' && this.divFaultDesc) {
        const dataFilter = alarmCategoryData.faultTable.filter(
          data => data.desc.indexOf(this.divFaultDesc) >= 0
        );
        alarmCategoryData.faultTableData = [...dataFilter];
        alarmCategoryData.faultLength = dataFilter.length;
        const dataFilter2 = alarmCategoryData.faultCountsData.filter(
          data => data.faultDesc.indexOf(this.divFaultDesc) >= 0
        );
        alarmCategoryData.faultCounts = [...dataFilter2];
        alarmCategoryData.faultCountLength = dataFilter2.length;
      } else {
        alarmCategoryData.faultTableData = [...alarmCategoryData.faultTable];
        alarmCategoryData.faultLength = alarmCategoryData.faultTableData.length;
        alarmCategoryData.faultCounts = [...alarmCategoryData.faultCountsData];
        alarmCategoryData.faultCountLength =
          alarmCategoryData.faultCounts.length;
      }
      this.faultFiler(alarmCategoryData);
    });
  }
  onClickLevel(
    event: HTMLInputElement,
    faultLevel: FaultLevel,
    alarmCategory: AlarmSearchData
  ) {
    faultLevel.isChecked = event.checked;
    this.faultCountDataFilter();
  }
  onClickTurbComponent(
    event: HTMLInputElement,
    turbComponent: TurbComponent,
    alarmCategory: AlarmSearchData
  ) {
    turbComponent.isChecked = event.checked;
    this.faultCountDataFilter();
  }
  faultFiler(alarmCategory: AlarmSearchData) {
    // 当前报警类别下的所有数据;
    //const alarmCategoryFaultData = this.faultDatas.filter(o => o.alarmCategoryId === alarmCategory.alarmCategoryId);
    const faultsList =
      alarmCategory.faultTableData; /* .forEach(fault => {
      const faults = {
        faultCode: fault.faultCode,
        desc: fault.farmName + fault.deviceName + fault.faultDesc,
        faultLevelName: fault.faultLevelName,
        components: fault.turbComponentName + '-' + fault.subcomponentName + '-' + fault.partsName,
        faultLevelColor: fault.faultLevelColor,
        faultTime: fault.faultTime,
        faultEndTime: fault.faultEndTime,
        faultLevelId: fault.faultLevelId,
        turbComponentId: fault.turbComponentId,
        turbComponent: fault.turbComponentName
      };
      faultsList.push(faults);
    }); */
    const list = new List(faultsList);
    // 计算报警等级数量
    alarmCategory.faultLevelTotals.forEach(level => {
      level.faultLevelCount = list.Count(
        o => o.faultLevelId === level.faultLevelId
      );
    });

    // 计算报警类别数量
    alarmCategory.turbComponentTotals.forEach(turbComponent => {
      turbComponent.turbComponentCount = list.Count(
        o => o.turbComponentId === turbComponent.turbComponentId
      );
    });
    // 报警等级数据过滤
    const tumLevelsData: FaultTableData[] = [];
    const levels = alarmCategory.faultLevelTotals.filter(o => o.isChecked);
    const levelsLen = levels.length;

    // 报警类别数据过滤
    const tumComponent: FaultTableData[] = [];
    const components = alarmCategory.turbComponentTotals.filter(
      o => o.isChecked
    );
    const componentLen = components.length;

    if (levelsLen > 0 && componentLen > 0) {
      faultsList.forEach(faultData => {
        if (
          levels.find(level => level.faultLevelId === faultData.faultLevelId)
        ) {
          tumLevelsData.push(faultData);
        }
      });

      faultsList.forEach(faultData => {
        if (
          components.find(
            component => component.turbComponentId === faultData.turbComponentId
          )
        ) {
          tumComponent.push(faultData);
        }
      });

      // 取两个数据的交集
      const filterdData: FaultTableData[] = tumLevelsData.filter(o => {
        return tumComponent.indexOf(o) > -1;
      });
      alarmCategory.faultTableData = filterdData;
      alarmCategory.faultLength = filterdData.length;
    } else if (levelsLen < 1 && componentLen > 0) {
      faultsList.forEach(faultData => {
        if (
          components.find(
            component => component.turbComponentId === faultData.turbComponentId
          )
        ) {
          tumComponent.push(faultData);
        }
      });
      alarmCategory.faultTableData = tumComponent;
      alarmCategory.faultLength = tumComponent.length;
    } else if (levelsLen > 0 && componentLen < 1) {
      faultsList.forEach(faultData => {
        if (
          levels.find(level => level.faultLevelId === faultData.faultLevelId)
        ) {
          tumLevelsData.push(faultData);
        }
      });
      alarmCategory.faultTableData = tumLevelsData;
      alarmCategory.faultLength = tumLevelsData.length;
    } else {
      alarmCategory.faultTableData = faultsList;
      alarmCategory.faultLength = faultsList.length;
    }
  }

  /* loadData(event: any, index: number) {
    setTimeout(() => {
      if (index) {
        this.alarmCategoryDatas[index].faultTableData = this.faultData2.slice(event.first, (event.first + event.rows));
      } else {
        this.alarmCategoryDatas[index].faultTableData = this.faultData1.slice(event.first, (event.first + event.rows));
      }
    }, 250);

  } */

  /* loadCountData(event: any, index: number) {
    setTimeout(() => {
      if (index) {
        this.alarmCategoryDatas[index].faultCounts = this.faultData3.slice(event.first, (event.first + event.rows));
      } else {
        this.alarmCategoryDatas[index].faultCounts = this.faultData4.slice(event.first, (event.first + event.rows));
      }

    }, 250);
  } */

  onResize(ev) {
    if (this.active === 0) {
      this.row = Math.floor(
        (this.alarmTable.nativeElement.clientHeight - 100) / 40
      );
      this.rowC = Math.floor(
        (this.alarmTable.nativeElement.clientHeight + 50) / 40
      );
    } else {
      this.row = Math.floor(
        (this.countTable.nativeElement.clientHeight - 150) / 40
      );
      this.rowC = Math.floor(
        (this.countTable.nativeElement.clientHeight - 50) / 40
      );
    }
  }

  onClickHeader(n: number) {
    this.active = n;
  }

  changeSort(ev) {
    if (!ev.order) {
      this.sortF = 'faultCount';
    } else {
      this.sortF = ev.field;
    }
  }

  changeFaultSort(ev) {
    if (!ev.order) {
      this.sortFault = 'faultCode';
    } else {
      this.sortFault = ev.field;
    }
  }

  public clear() {
    this.isShowBar = false;
    this.alarmCategoryDatas.forEach(alarmCategoryData => {
      alarmCategoryData.faultCounts = [];
      alarmCategoryData.faultTableData = [];
    });
  }
  exportData() {
    this.isShowBar = true;
    const fomat = 'yyyy-MM-dd HH:mm:ss',
      start = this.datePipe.transform(this.startTime, fomat),
      end = this.datePipe.transform(this.endTime, fomat);
    let str = ` <table id="ex-tab-alarmList" border="1">
    <caption border="1">${start}--${end}历史报警</caption>
    <thead>
      <tr>
        <th>序号</th>
        <th>风场名称</th>
        <th>故障设备</th>
        <th>风机厂家</th>
        <th>风机编号</th>
        <th>故障码</th>
        <th>设备主部件</th>
        <th>设备分部件</th>
        <th>设备子部件</th>
        <th>故障描述</th>
        <th>故障开始时间</th>
        <th>故障结束时间</th>
        <th>故障持续时间(h)</th>
        <th>检修完成时间</th>
        <th>等待备件时间</th>
        <th>累计时间</th>
        <th>损失电量</th>
        <th>处理情况</th>
        <th>更换备件</th>
      </tr>
    </thead>
    <tbody>`;
    const len = this.alarmCategoryDatas[0].faultTableData.length;

    for (let i = 0; i < len; i++) {
      const item = this.alarmCategoryDatas[0].faultTableData[i];
      const faultTime = this.datePipe.transform(item.faultTime, fomat),
        faultEndTime = this.datePipe.transform(item.faultEndTime, fomat);
        str += `<tr >
        <td>${ i + 1}</td>
        <td>${item.farmName}</td>
        <td>风机</td>
        <td>${item.factoryName}</td>
        <td>${item.deviceName}</td>
        <td>${item.faultCode}</td>
        <td>${item.turbComponent}</td>
        <td>${item.subcomponentName}</td>
        <td>${item.partsName}</td>
        <td>${item.faultDesc}</td>
        <td>${faultTime }</td>
        <td>${item.faultEndTime}</td>
        <td>${(item.faultContinueTime || item.faultContinueTime === 0) ? item.faultContinueTime : ''}</td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>`;
    }
    str += `</tbody>
  </table>`;
  var html = '<html><head><meta charset="utf-8" /></head><body >' + str + '</body></html>';

  // 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
  var blob = new Blob([html], { type: 'application/vnd.ms-excel' });
  // var a = document.getElementsByTagName('a')[0];
  // 利用URL.createObjectURL()方法为a元素生成blob URL
  var href = URL.createObjectURL(blob);
  document.getElementById('ex').setAttribute('href', href);

  // // 设置文件名，目前只有Chrome和FireFox支持此属性
  document.getElementById('ex').setAttribute('download', '历史报警.xls');
  this.isShowBar = false;
  // a.download = '实际功率曲线.xls';
  // a.click();
  // document.getElementById('ex').click();
  }
}



// WEBPACK FOOTER //
// ./src/app/module/alarm/alarm-search/alarm-list/alarm-list.component.ts
